package com.mediacloud.app.newsmodule.view;

import static com.utils.EmotionsUtilsKt.decodeFaceFormStr;
import static com.utils.EmotionsUtilsKt.setFace;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chinamcloud.asr.AsrEventListener;
import com.chinamcloud.asr.IAsrCommentProvider;
import com.chinamcloud.collect.AcquisitionManager;
import com.eventTrack.TXReportManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.mediacloud.app.asr.BsgDownload;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.ICommentObj;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.utils.ViewUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.model.NewsCommentItem;
import com.mediacloud.app.newsmodule.model.ReplyCommentItem;
import com.mediacloud.app.newsmodule.model.ReplyListHelper;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.AppPermissionUtils;
import com.mediacloud.app.newsmodule.utils.CommentPublishInvoker;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.ReplyCommentInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.spider.IAccessToken;
import com.mediacloud.app.newsmodule.utils.spider.SpiderKit;
import com.mediacloud.app.newsmodule.view.adapter.EmojiAdapter;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.view.SimpleDialog;
import com.mediacloud.app.user.model.UserInfo;
import com.utils.EmotionsUtilsKt;
import com.utils.WatchManManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CommentPopupWindow extends PopupWindow implements AsrEventListener, View.OnClickListener, View.OnLongClickListener {

    public TextView writeComment;
    public EditText commentInputText;
    public ICommentObj articleItem;
    private ReplyCommentInvoker mReplyCommentInvoker;
    private CommentPublishInvoker commentPublishInvoker;
    private SubmitCommentCallBack callBack;
    public SubmitCommentListener commentListener;
    private SimpleDialog simpleDialog;
    protected Context mContext;
    public OnCommentPublishListener onCommentPublishListener;
    private String VIEW_LOG_TAG = "test";
    private View mView;
    private View copyandpaste;
    private ClipboardManager mClipboard = null;
    public boolean isReply = false;
    public boolean isSpider = false;
    public String access_token;
    private long comment_id;
    private String reply_avatar;
    private String reply_nickname = "";
    private String reply_uid = "";
    private CheckBox anonymousCheckBox;
    private int anonymous = 0;
    public int type = 1;

    /**
     * 提交评论时的监听,在调用接口之前
     */
    private OnCommentListener onCommentListener;

    private ImageView ivEmoji;//军号表情Emoji
    private RecyclerView rcyEmoji;
    private EmojiAdapter emojiAdapter;
    private boolean isShowEmoji = false;


    TextView statusText;
    ImageView inputModeImg;
    View voiceInputLayout;
    ImageView voiceInputBtn;
    private CheckBox mChange;
    private LinearLayout mMemes;
    private TabLayout mTl;
    private ViewPager2 mVp;
    private RelativeLayout topContent;
    private IAsrCommentProvider asrCommentProvider;
    private InputMethodManager imm;


    public boolean isIm = false;


    public void setOnCommentListener(OnCommentListener onCommentListener) {
        this.onCommentListener = onCommentListener;
    }


    @SuppressLint("WrongConstant")
    public CommentPopupWindow(FragmentActivity context) {
        super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        asrCommentProvider = ARouter.getInstance().navigation(IAsrCommentProvider.class);
        if (asrCommentProvider != null) {
            asrCommentProvider.init(context, this);
        }
        setBackgroundDrawable(context.getResources().getDrawable(R.color.trans_black));
        setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        mContext = context;
        setOutsideTouchable(true);
        setFocusable(true);
        mView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_layout_comment_input_x, null);
        voiceInputBtn = mView.findViewById(R.id.voiceInputBtn);
        inputModeImg = mView.findViewById(R.id.inputModeImg);
        ivEmoji = mView.findViewById(R.id.ivEmoji);
        rcyEmoji = mView.findViewById(R.id.rcyEmoji);
        commentInputText = mView.findViewById(R.id.commentInputText);
        topContent = mView.findViewById(R.id.topContent);
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mView.findViewById(R.id.view_bg).setOnClickListener(v -> dismiss());
        if (AppFactoryGlobalConfig.getAppServerConfigInfo(context).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(context).getOtherFunction().voice_comment == 1) {
            inputModeImg.setVisibility(View.VISIBLE);
            if (asrCommentProvider == null) {
                inputModeImg.setVisibility(View.GONE);
            }
        } else {
            mChange = mView.findViewById(R.id.comment_memes_keyboard);
            mMemes = mView.findViewById(R.id.comment_memes);
            mTl = mView.findViewById(R.id.comment_memes_tl);
            mVp = mView.findViewById(R.id.comment_memes_vp);
            mMemes.setVisibility(View.GONE);
            inputModeImg.setVisibility(View.GONE);
            ivEmoji.setVisibility(View.GONE);
            mVp.setAdapter(new FragmentStateAdapter(context.getSupportFragmentManager(), context.getLifecycle()) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
//                    MMKV mmkv = MMKV.mmkvWithID(mPackageIdList.get(position));
//                    String[] keyArray = mmkv.allKeys();
                    List<String> emojiIdList = new ArrayList<>();
                    List<String> urlList = new ArrayList<>();
//                    if (null != keyArray) {
//                        emojiIdList = Arrays.asList(keyArray);
//                        for (String key : keyArray) {
//                            urlList.add(mmkv.decodeString(key));
//                        }
//                    }
                    List<String> emoji = EmotionsUtilsKt.getMEmojiMap().get(EmotionsUtilsKt.getMTabTitleList().get(position));
                    for (int j = 0; j < emoji.size(); j++) {
                        String s = emoji.get(j);
                        String[] split = s.split(",");
                        emojiIdList.add(split[0]);
                        urlList.add(split[1]);
                    }

                    return new MemesFragment(position, commentInputText, emojiIdList, urlList);
                }

                @Override
                public int getItemCount() {
                    return EmotionsUtilsKt.getMTabTitleList().size();
                }
            });
            new TabLayoutMediator(mTl, mVp, (tab, position) -> tab.setText(EmotionsUtilsKt.getMTabTitleList().get(position))).attach();
            commentInputText.setOnTouchListener((v, event) -> {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    commentInputText.setFocusable(true);
                    commentInputText.setFocusableInTouchMode(true);
                    commentInputText.requestFocus();
                    commentInputText.findFocus();
                    mMemes.setVisibility(View.GONE);
                    mChange.setChecked(false);
                }
                return false;
            });
            mChange.setOnCheckedChangeListener((compoundButton, b) -> {
                if (compoundButton.isChecked()) {
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(commentInputText.getWindowToken(), 0);

                    mMemes.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mMemes.setVisibility(View.VISIBLE);
                            commentInputText.setFocusable(false);
                        }
                    }, 120);
                    topContent.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            TranslateAnimation translate1Anim = new TranslateAnimation(0.0f, 0.0f, 600.0f, 0.0f);
                            translate1Anim.setFillAfter(true);
                            translate1Anim.setDuration(300);
                            topContent.startAnimation(translate1Anim);
                            topContent.setVisibility(View.VISIBLE);
                        }
                    }, 250);
                } else {
                    commentInputText.setFocusable(true);
                    commentInputText.setFocusableInTouchMode(true);
                    commentInputText.requestFocus();
                    commentInputText.findFocus();
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(commentInputText, 0);
                    mMemes.setVisibility(View.GONE);
                }
            });
        }
        voiceInputLayout = mView.findViewById(R.id.voiceInputLayout);
        statusText = mView.findViewById(R.id.statusText);
        setContentView(mView);

        setAnonymousView();
        initChild(mContext);
        initDataInvoker();
        commentInputText.setOnLongClickListener(this);
        mClipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        inputModeImg.setOnClickListener(v -> {

            if (inputModeImg.getTag() == null) {
                voiceInputMode();
            } else {
                keyInputMode();
            }

        });
        voiceInputBtn.setOnClickListener(v -> {
            if (status != Status.PROCESSING) {
                String[] permissions = {Manifest.permission.RECORD_AUDIO};
                AppPermissionUtils.doAuthPermissionCall(ViewUtils.searchTintContextHostActivity(mContext), aBoolean -> {
                    if (aBoolean) {
                        start();
                        voiceInputBtn.setImageResource(R.drawable.vocie_input_complete);
                        status = Status.PROCESSING;
                    }
                }, permissions, true);
            } else {
                stop();
                voiceInputBtn.setImageResource(R.drawable.voice_helper_microphone);
            }
        });
    }


    public void voiceInputMode() {
        InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(commentInputText.getWindowToken(),
                0);
        inputModeImg.setImageResource(R.drawable.input_mode_keyborad);
        inputModeImg.setTag(1);
        voiceInputLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                voiceInputLayout.setVisibility(View.VISIBLE);
            }
        }, 300);
    }

    public void keyInputMode() {
        hideEmoji();
        inputModeImg.setTag(null);
        inputModeImg.setImageResource(R.drawable.icon_voice_input);
        voiceInputLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputmanger.showSoftInput(commentInputText, 0);
            }
        }, 300);
        voiceInputLayout.setVisibility(View.GONE);
    }


    private void initDataInvoker() {
        ReplyCommentCallBack mReplyCommentCallBack = new ReplyCommentCallBack();
        mReplyCommentInvoker = new ReplyCommentInvoker(mReplyCommentCallBack);
    }

    SpannableString ss;

    private void pasteToResult() {
        String resultString = "";
        // 检查剪贴板是否有内容
        if (mClipboard.hasPrimaryClip()) {
            ClipData clipData = mClipboard.getPrimaryClip();
            int count = clipData.getItemCount();
            for (int i = 0; i < count; ++i) {
                ClipData.Item item = clipData.getItemAt(i);
                CharSequence str = item.coerceToText(mContext);
                //Log.i("mengdd", "item : " + i + ": " + str);
                resultString += str;
            }
        }

        commentInputText.append(decodeFaceFormStr(resultString, commentInputText.getContext()));
        commentInputText.setSelection(commentInputText.getText().length());
    }

    protected void initChild(final Context context) {
        simpleDialog = new SimpleDialog(context);
        callBack = new SubmitCommentCallBack();
        commentPublishInvoker = new CommentPublishInvoker(callBack);
        copyandpaste = mView.findViewById(R.id.copyandpaste);
        copyandpaste.setOnClickListener(this);
        writeComment = mView.findViewById(R.id.write_comment);

        /*StateListDrawable drawable = (StateListDrawable) writeComment.getBackground();
        GradientDrawable drawable1 = (GradientDrawable) drawable.getStateDrawable(1);
        drawable1.setColor(DefaultBgUtil.getTintColor(mContext));*/
        // writeComment.setBackground(drawable);

        float size = mContext.getResources().getDimensionPixelSize(R.dimen.dimen_16sp);
        commentInputText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        commentInputText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                copyandpaste.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
                copyandpaste.setVisibility(View.GONE);
                if (TextUtils.isEmpty(s.toString())) {
                    writeComment.setEnabled(false);
                } else {
                    writeComment.setEnabled(true);
                }
            }
        });
        commentInputText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                }
            }
        });

        commentInputText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyInputMode();
            }
        });

        writeComment.setOnClickListener(this);

    }

    //是否开启匿名回复
    public void setAnonymousView() {
        anonymousCheckBox = mView.findViewById(R.id.anonymousCheckBox);
        if (/*mContext.getResources().getString(R.string.needAnonymous).equals("0")*/AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).getOtherFunction().getAnonymous_comment() <= 0 || isSpider)
            anonymousCheckBox.setVisibility(View.GONE);
        anonymousCheckBox.setOnCheckedChangeListener((compoundButton, b) -> {
            if (compoundButton.isChecked()) {
                anonymousCheckBox.setTextColor(mContext.getResources().getColor(R.color.style_blue));
                anonymous = 1;
            } else {
                anonymous = 0;
                anonymousCheckBox.setTextColor(mContext.getResources().getColor(R.color.color_333333));
            }
        });

    }

    //传入需要回复的评论对象
    public void setReplyData(NewsCommentItem data) {
        comment_id = data.getCommentid();
        reply_avatar = data.getAvatar();
        reply_nickname = data.getNickname();
        reply_uid = data.getUid();
    }

    public void setReplyData(ReplyCommentItem data) {
        comment_id = data.getParentCid();
        reply_avatar = data.getAvatar();
        reply_nickname = data.getNickName();
        reply_uid = data.getUid();
    }

    private void submitCommunityReplay() {

      /*  if (commentInputText.getText().length() == 0) {
            ToastUtil.show(mContext, R.string.comment_cantnull);
            return;
        }*/
        UserInfo info = UserInfo.getUserInfo(mContext);
        if (info.isLogin()) {
            if (!simpleDialog.isShowing()) {
                simpleDialog.show();
                simpleDialog.updateText(R.string.comment_submit);
            }
            verifyTokenToLogin(String.valueOf(comment_id), commentInputText.getText().toString(), info);
        } else {
            intoLogin(mContext);
        }
    }


    private void submitCommentReplay() {
        if (commentInputText.getText().length() == 0) {
            ToastUtil.show(mContext, R.string.comment_cantnull);
            return;
        }
        UserInfo info = UserInfo.getUserInfo(mContext);
        if (info.isLogin()) {
            simpleDialog.show();
            simpleDialog.updateText(R.string.comment_submit);
            verifyTokenToLogin(String.valueOf(comment_id), commentInputText.getText().toString(), info);
        } else {
            intoLogin(mContext);
        }
        iniAnonymousStatus();
    }

    private void verifyTokenToLogin(String commentContentID, String content, UserInfo userInfo) {
        if (mContext == null) {
            return;
        }
        toCommentNext(content, userInfo);
//        WatchManManager.INSTANCE.getCommentTokenToVerifyToken(mContext,
//                mContext.getString(R.string.tenantid),
//                commentContentID, content, new Observer<JSONObject>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(@NonNull JSONObject jsonObject) {
//
//                        try {
//                            //史志勇  state 非200 报这个提示
//                            if (jsonObject != null && jsonObject.optInt("state", 0) == 200) {
//                                toCommentNext(content, userInfo);
//                            } else {
//                                if (simpleDialog != null) {
//                                    simpleDialog.dismiss();
//                                }
//                                ToastUtil.showToastCenter(mContext, "您的评论内容不符合规范,请重新评论" );
//
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable e) {
//
//                        try {
//                            if (simpleDialog != null) {
//                                simpleDialog.dismiss();
//                            }
//                            ToastUtil.showCustomView(mContext, "网络异常，请检查网络");
//                        } catch (Exception ex) {
//                            ex.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
    }

    private void toCommentNext(String content, UserInfo info) {
        if (isSpider) {
            if (!TextUtils.isEmpty(access_token)) {
                commentPublishInvoker.publishCommunityComment(articleItem.getId() + "", access_token,
                        content, "" + comment_id, reply_uid);
            } else {
                SpiderKit.INSTANCE.getAccessToken(mContext, info, new IAccessToken() {
                    @Override
                    public void success(@NonNull UserInfo userInfo) {
                        publishContent();
                    }

                    @Override
                    public void fail() {

                    }
                });
            }
        } else {
            mReplyCommentInvoker.submitReplayComment(mContext, type,articleItem.getTitle(),
                    "" + articleItem.getCatalogId(), info.getAvatar(),
                    "" + comment_id, content, info.getNickname()
                    , articleItem.getId() + "", reply_avatar, info.getUserid(), anonymous + "");
        }
        if (isSpider) {
            if (!TextUtils.isEmpty(access_token)) {
                commentPublishInvoker.publishCommunityComment(articleItem.getId() + "", access_token, content);
            } else {

                SpiderKit.INSTANCE.getAccessToken(mContext, info, new IAccessToken() {
                    @Override
                    public void success(@NonNull UserInfo userInfo) {
                        try {
                            publishContent();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void fail() {

                    }
                });
            }
        } else {
            String uid = info.getUserid();
            commentPublishInvoker.publishComment(type, info.getAvatar(), info.getNickname(), articleItem, uid, content, anonymous, mContext);
            iniAnonymousStatus();
        }
    }

    protected void iniAnonymousStatus() {
        anonymous = 0;
        anonymousCheckBox.setChecked(false);
    }

    @Override
    public void onClick(View v) {

        if (v == copyandpaste) {
            copyandpaste.setVisibility(View.GONE);
            pasteToResult();
        } else if (v == writeComment) {
            if (FunKt.isFastClick())
                publishContent();
        }
    }

    @Override
    public boolean onLongClick(View v) {
        copyandpaste.setVisibility(View.VISIBLE);
        return false;
    }

    protected void intoLogin(Context context) {
//        ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source =LoginUtils.source_comment;
        LoginUtils.invokeLogin(context);
    }

    public void show(View container) {
        if (!UserInfo.isLogin(container.getContext())) {
            LoginUtils.request_source =LoginUtils.source_comment;
            LoginUtils.invokeLogin(container.getContext());
            return;
        }
        topContent.setVisibility(View.GONE);
        imm.toggleSoftInput(0, InputMethodManager.RESULT_HIDDEN);
        topContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                //构建属性动画-平移动画
                TranslateAnimation translate1Anim = new TranslateAnimation(0.0f, 0.0f, 150.0f, 0.0f);
                //动画结束后是否停留在移动后位置，true为停留
                translate1Anim.setFillAfter(true);
                //动画执行时间（单位：毫秒）
                translate1Anim.setDuration(150);
                topContent.startAnimation(translate1Anim);
                topContent.setVisibility(View.VISIBLE);
            }
        }, 250);
        hideEmoji();
        inputModeImg.setImageResource(R.drawable.icon_voice_input);
        inputModeImg.setTag(null);
        voiceInputLayout.setVisibility(View.GONE);
        copyandpaste.setVisibility(View.GONE);
        showAtLocation(container, Gravity.BOTTOM, 0, 0);
        commentInputText.setFocusable(true);
        commentInputText.setFocusableInTouchMode(true);
        commentInputText.requestFocus();

    }

    @Override
    public void dismiss() {
        InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(commentInputText.getWindowToken(), 0);
        if (asrCommentProvider != null) {
            asrCommentProvider.sendCancel();
        }
        super.dismiss();
        mMemes.setVisibility(View.GONE);
        mChange.setChecked(false);
    }


    public void destory() {
        if (simpleDialog != null)
            simpleDialog.dismiss();
        simpleDialog = null;
        commentListener = null;
        if (commentPublishInvoker != null)
            commentPublishInvoker.destory();
        commentPublishInvoker = null;
        if (asrCommentProvider != null) {
            asrCommentProvider.release();
        }
    }


    private void publishContent() {
        String content = commentInputText.getText().toString();
        if (TextUtils.isEmpty(content.trim())) {//去空格
            ToastUtil.show(mContext, "请输入评论内容");
            return;
        }

        UserInfo info = UserInfo.getUserInfo(mContext);
        if (!info.isLogin()) {
            intoLogin(mContext);
            return;
        }
        if (isIm) {
            if (onCommentListener != null) {
                onCommentListener.onComment(content, reply_nickname, reply_uid);
            }
            return;
        }
        if (isReply) {
            if (isSpider) submitCommunityReplay();
            else submitCommentReplay();
        } else {
            if (!simpleDialog.isShowing()) {
                simpleDialog.show();
                simpleDialog.updateText(R.string.comment_submit);
            }
            if (isSpider) {
                verifyTokenToLogin(String.valueOf(articleItem.getId()), content, info);
            } else {
                verifyTokenToLogin(String.valueOf(articleItem.getId()), content, info);
            }
            if (isSpider) {
                if (!TextUtils.isEmpty(access_token)) {
                    commentPublishInvoker.publishCommunityComment(articleItem.getId() + "", access_token, content);
                } else {

                    SpiderKit.INSTANCE.getAccessToken(mContext, info, new IAccessToken() {
                        @Override
                        public void success(@NonNull UserInfo userInfo) {
                            publishContent();
                        }

                        @Override
                        public void fail() {

                        }
                    });
                }
            } else {
                String uid = info.getUserid();
                commentPublishInvoker.publishComment(type, info.getAvatar(), info.getNickname(), articleItem, uid, content, anonymous, mContext);
                iniAnonymousStatus();
            }
        }
        if (onCommentListener != null) {
            onCommentListener.onComment(content, reply_nickname, reply_uid);
        }
    }

    int lastPosition = 0;

    @Override
    public void onAsrPartial(@Nullable String params, @Nullable byte[] data, int offset, int length) {
        try {
            JSONObject resultJson = new JSONObject(params);
            recognResult = resultJson.optString("best_result", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (params != null && params.contains("\"nlu_result\"")) {
            if (length > 0 && data.length > 0) {
                String result = new String(data, offset, length);
                //Log.w("APPTAG", "" + result);
                commentInputText.append(result);
            }
        }
    }

    @Override
    public void onAsrExit(@Nullable String params, @Nullable byte[] data, int offset, int length) {
        voiceInputBtn.setImageResource(R.drawable.voice_input_center);
        status = Status.IDLE;
        //Log.w("APPTAG", "recognResult:" + recognResult);
        status = Status.IDLE;
        lastPosition = 0;
        if (TextUtils.isEmpty(recognResult)) {
//                ToastUtil.show(this,"没有识别出");
        } else {
            commentInputText.append(recognResult);
        }
        statusText.setText(R.string.comment_voiceparse);
    }

    public interface OnCommentListener {
        void onComment(@NonNull String content, String beReplayUserName, String beReplayUserId);
    }

    public interface SubmitCommentListener {
        void success();

        void failed();
    }

    public interface OnCommentPublishListener {
        void onComment(String content);

    }

    /**
     * 提交评论的回调
     */
    class SubmitCommentCallBack implements DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver data) {
            try {
                simpleDialog.dismiss();
                if (data.state) {
                    //评论数据采集
                    final UserInfo info = UserInfo.getUserInfo(mContext);
                    String comment = commentInputText.getText().toString();
                    AcquisitionManager p = AcquisitionManager.getInstance();
                    if (articleItem != null) {
                        p.comment(info, articleItem.getId() + "", DomainUtil.getDomain(articleItem.getUrl())
                                , articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent(), comment);
                    }
                    if (onCommentPublishListener != null) {
                        onCommentPublishListener.onComment(comment);
                    }
                    commentInputText.getText().clear();
                    ToastUtil.showCustomView(mContext, R.string.comment_success);
                    if (articleItem != null) {

                        if(articleItem instanceof ArticleItem){
                            TXReportManager.getInstance().app_jhapp_content_detail_interact("评论","","",(ArticleItem) articleItem);
                        }else{
                            TXReportManager.getInstance().app_jhapp_content_detail_interact("评论","","",null);
                        }
                    }
                    String isStudy = "0";
                    if (articleItem instanceof ArticleItem) {
                        if (((ArticleItem) articleItem).getMovie() != null && ((ArticleItem) articleItem).getMovie().getIsStudyContent() != null) {
                            isStudy = "1".equals(((ArticleItem) articleItem).getMovie().getIsStudyContent()) ? "1" : "0";
                        }
                    }
                    if (articleItem != null) {
                        if(articleItem instanceof ArticleItem){
                            Addintegral.addintegral(mContext, articleItem.getId(), 3, isStudy,(ArticleItem)articleItem);
                        }else{
                            Addintegral.addintegral(mContext, articleItem.getId(), 3, isStudy,null);
                        }
                    } else {
                        Addintegral.addintegral(mContext, 3, isStudy,null);
                    }
                    if (commentListener != null)
                        commentListener.success();
                } else {
                    fault(null);
                }
                //Log.w(VIEW_LOG_TAG, "success" + data);
                dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void fault(Object data) {
            try {
                //Log.w(VIEW_LOG_TAG, "fault" + data);
                ToastUtil.show(mContext, R.string.comment_failed);
                if (commentListener != null)
                    commentListener.failed();
                simpleDialog.dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    class ReplyCommentCallBack implements DataInvokeCallBack<ReplyListHelper> {
        @Override
        public void success(ReplyListHelper data) {
            try {
                simpleDialog.dismiss();
                if (data.state) {
                    commentInputText.getText().clear();
                    ToastUtil.showCustomView(mContext, R.string.comment_success);
                    String isStudy = "0";
                    if (articleItem instanceof ArticleItem && ((ArticleItem) articleItem).getMovie() != null) {
                        isStudy = "1".equals(((ArticleItem) articleItem).getMovie().getIsStudyContent()) ? "1" : "0";
                    }
                    //返回提交审核成功，提交。
                    if (articleItem != null) {
                        if(articleItem instanceof ArticleItem){
                            Addintegral.addintegral(mContext, articleItem.getId(), 3, isStudy,(ArticleItem)articleItem);
                        }else{
                            Addintegral.addintegral(mContext, articleItem.getId(), 3, isStudy,null);
                        }
                    } else {
                        Addintegral.addintegral(mContext, 3, isStudy,null);
                    }
                    if (commentListener != null)
                        commentListener.success();
                } else {
                    fault(null);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void fault(Object data) {
            try {
                ToastUtil.show(mContext, R.string.comment_failed);
                if (commentListener != null)
                    commentListener.failed();
                simpleDialog.dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    Status status = Status.IDLE;

    enum Status {
        IDLE, PROCESSING
    }

    String recognResult = "";

    /**
     * 基于SDK集成2.2 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    private synchronized void start() {
//        txtLog.setText("请说话 正在聆听……");
        recognResult = "";
        statusText.setText(R.string.is_listen_pleasesay);
        if (asrCommentProvider != null) {
            asrCommentProvider.start(BsgDownload.getSavePath());
        }
    }

    /**
     * 点击停止按钮
     * 基于SDK集成4.1 发送停止事件
     */
    private void stop() {
        statusText.setText(R.string.comment_voiceparse);
        if (asrCommentProvider != null) {
            asrCommentProvider.sendStop();
        }
    }

    public void hideEmoji() {
        if (rcyEmoji != null) {
            isShowEmoji = false;
            rcyEmoji.setVisibility(View.GONE);
        }

    }

    //供本类中ViewPager2调用的内部公共静态Fragment类
    public static class MemesFragment extends BaseFragment {
        private final List<String> idList, urlList;  //表情代号和链接地址
        private int position;
        private RecyclerView mMemes;
        private EditText editText;  //拿到输入框的实例

        public MemesFragment(int position, EditText editText, List<String> idList, List<String> urlList) {
            this.position = position;
            this.editText = editText;
            this.urlList = urlList;
            this.idList = idList;
        }

        @Override
        public int getLayoutResID() {
            return R.layout.fragment_memes;
        }

        @Override
        public void initView() {
            mMemes = getView().findViewById(R.id.rv_memes);
            //删除键
            getView().findViewById(R.id.v_memes_delete).setOnClickListener(v -> {
                int keyCode = KeyEvent.KEYCODE_DEL;
                KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
                KeyEvent keyEventUp = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
                editText.onKeyDown(keyCode, keyEventDown);
                editText.onKeyUp(keyCode, keyEventUp);
            });
            initEmoji();
        }

        private void initEmoji() {
            EmojiAdapter emojiAdapter = new EmojiAdapter(getContext());
            View footer = new View(getContext());
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(-1, getContext().getResources().getDimensionPixelSize(R.dimen.dimen34));
            footer.setLayoutParams(lp);
            footer.setBackgroundColor(Color.WHITE);
            emojiAdapter.addFooterView(footer);
            mMemes.setLayoutManager(new GridLayoutManager(getContext(), 5));
            mMemes.setAdapter(emojiAdapter);
            mMemes.getLayoutParams().height = emojiAdapter.getHeight() * 3;
            emojiAdapter.setNewData(urlList);
            emojiAdapter.setOnItemClickListener((adapter, view, position) -> {
                setFace(getContext(), editText, idList.get(position));
            });
        }
    }

}